package com.ldk.api;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.ldk.base.framework.util.ConfigUtil;
import com.ldk.base.framework.util.FileUtil;
import com.ldk.base.framework.util.PropertiesUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.Driver;
import com.ldk.framework.entity.User;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.IUserService;

/**
 * 控制器的基类
 * @author xiangwl
 * @version v1.0
 */
@Component("baseController")
public abstract class BaseController {
	
	@Autowired
	private IUserService userService;
	@Autowired
	private IDriverService driverService;
	
	protected BaseController(){
	}
	
	/**
	 * 默认日志
	 */
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	
	/**
	 * 获取config.properties的文件路径
	 * @return
	 */
	protected String getConfigPath(){
		return Consts.DEBUG ? this.getClass().getResource("/").getPath() +"/config_debug.properties" : 
							  this.getClass().getResource("/").getPath() +"/config.properties";
	}
	
	/**
	 * 获取图片根地址
	 * @return
	 */
	protected String getImageRoot(){
		Properties cfgProps = ConfigUtil.GetInstance().getConfig();
		String imgRoot = PropertiesUtil.getProperty(cfgProps, Consts.IMAGE_ROOT);
		if(!StringUtils.isEmpty(imgRoot)){
			imgRoot = imgRoot.replace("\\", "/");
		}
		if(!StringUtils.isEmpty(imgRoot) && !imgRoot.endsWith("/")){
			imgRoot += "/";
		}
		
		return imgRoot;
	}
	
	/**
	 * 获取图片存放的根路径
	 * @return
	 */
	protected String getImagePath(){
		Properties cfgProps = ConfigUtil.GetInstance().getConfig();
		String imgPath = PropertiesUtil.getProperty(cfgProps, Consts.IMAGE_PATH);
		if(!StringUtils.isEmpty(imgPath)){
			imgPath = imgPath.replace("\\", "/");
		}
		if(!StringUtils.isEmpty(imgPath) && !imgPath.endsWith("/")){
			imgPath += "/";
		}
		return imgPath;
	}
	
	/**
	 * 保存文件
	 * @param dir 保存目录
	 * @param file 文件
	 * @return
	 */
	protected FileItem saveFile(String dir, MultipartFile file){
		if(file == null || file.isEmpty()){
			return null;
		}
		try{
			FileItem fileItem = new FileItem();
			
			String imgPath = getImagePath();
			String folder = String.format("%s/%s", imgPath, dir);
			String orgfileName = file.getOriginalFilename();
			String ext = FileUtil.getFileExtention(orgfileName);
			if(StringUtils.isEmpty(ext)){
				String contentType = file.getContentType();
				if(contentType.equalsIgnoreCase("image/png")){
					ext = ".png";
				}
				else if(contentType.equalsIgnoreCase("image/jpg")){
					ext = ".jpg";
				}
				else if(contentType.equalsIgnoreCase("image/jpeg")){
					ext = ".jpeg";
				}
				else if(contentType.equalsIgnoreCase("image/gif")){
					ext = ".gif";
				}
				else if(contentType.equalsIgnoreCase("image/tiff")){
					ext = ".tiff";
				}
			}
			String fileName = (SystemUtil.generateOrderNo("") + ext) ;
			
			fileItem.setFileName(fileName);
			fileItem.setFileOldName(orgfileName);
			//保存
			Boolean saved = FileUtil.saveFile(folder, fileName, file.getBytes());
			if(saved){
				String fileRoot = getImageRoot();
				if(!StringUtils.isEmpty(dir)){
					dir = dir.replace("\\", "/");
				}
				if(!StringUtils.isEmpty(dir) && dir.startsWith("/")){
					dir = dir.substring(1);
				}
				String fullUrl = String.format("%s%s/%s", fileRoot, dir, fileName);
				String url = String.format("%s/%s", dir, fileName);
				fileItem.setFileFullUrl(fullUrl);
				fileItem.setFileUrl(url);
			}
			
			return fileItem;
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		return null;
	}
	
	/**
	 * 验证Token
	 * @param tokenKey
	 * @param tokenKeyValue
	 * @param token
	 * @return
	 */
	protected Boolean checkToken(String tokenKey, String tokenKeyValue, String token, RequestPlatform platform) {
		if(StringUtils.isEmpty(tokenKeyValue))
			return false;
		if(StringUtils.isBlank(token))
			return false;
		//用户Token验证
		Map<String, Object> query = new HashMap<String, Object>();
		query.put(tokenKey, tokenKeyValue);
		if(platform == RequestPlatform.client){
			User user = userService.selectOne("", query);
			if(user != null && token.toLowerCase().equals(user.getToken()))
				return true;
		}
		else if(platform == RequestPlatform.driver){
			Driver driver = driverService.selectOne("", query);
			if(driver != null && token.toLowerCase().equals(driver.getToken()))
				return true;
		}
		return false;
	}
}
